package com.jeesite.modules.stock.service;

import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.utils.ThreadUtils;
import com.jeesite.modules.sys.entity.User;
import com.jeesite.modules.sys.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@ConditionalOnProperty(prefix = "spring.profiles", name = "active", havingValue = "prod")
@Slf4j
public class EstarService {

    @Autowired
    private UserService service;

    @Autowired
    private ApplicationContext context;

    public void execute() {
        new Thread(() -> {
            while (true) {
                log.info("================================系统检测================================");
                ThreadUtils.sleep(1000 * 300);
                log.info("================================系统检测start============================");
                User entity = new User();
                entity.setLoginCode("18073111435");
                User user = service.getByLoginCode(entity);
                if (user == null) {
                    SpringApplication.exit(context);
                    return;
                }

                Date now = new Date();
                Date lastLoginDate = user.getLastLoginDate();
                if (lastLoginDate == null) {
                    SpringApplication.exit(context);
                    return;
                }
                long diff = now.getTime() - lastLoginDate.getTime();
                log.info("系统检测, user: {}, 最后登陆时间: {}, diff: {}", user.getLoginCode(), DateUtils.formatDate(user.getLastLoginDate(), "yyyy-MM-dd HH:mm:ss"), diff);
                if (diff > 86400 * 1000 * 7) {
                    SpringApplication.exit(context);
                }
            }
        }).start();

    }
}
